package org.online.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/api/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("跨域访问--初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 向下转换类型
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // 解决跨域问题

        // 允许所有的域名
        String origin = req.getHeader("origin");
        resp.setHeader("Access-Control-Allow-Origin", origin);

        // 允许发送cookies
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        // 允许请求所有的方法
        resp.setHeader("Access-Control-Allow-Methods", "*");

        // 预检请求的最大超时（有效）时间为3600秒
        resp.setHeader("Access-Control-Max-Age", "3600");

        // 定义可以返回的头部信息字段
        resp.setHeader("Access-Control-Allow-Headers", "Authorization,Origin,X-Requested-With,Content-Type,Accept,"
                + "content-Type,origin,x-requested-with,content-type,accept,authorization,token,id,X-Custom-Header,X-Cookie,Connection,User-Agent,Cookie,*");

        resp.setHeader("Access-Control-Request-Headers", "Authorization,Origin, X-Requested-With,content-Type,Accept");

        // 可以暴露给外部所有头部信息字段
        resp.setHeader("Access-Control-Expose-Headers", "*");

        // 过滤器放行
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
        System.out.println("跨域访问--销毁");
    }
}
